package com.gome.ocean.service.task;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;

import com.gome.ocean.common.enums.DataBaseType;
import com.gome.ocean.common.utils.SpringContextUtil;
import com.gome.ocean.dao.model.gddl.AppRuleBO;
import com.gome.ocean.service.gddl.AppRuleService;
import com.gome.ocean.service.task.DataSourceWrapper.TableCheck;


/**
 * 检测表大小
 * 
 * @author haqiaolong 2016年4月15日 上午10:55:33
 * @since 5.0.0
 */
public class CheckDataSourceTableJobTask extends ScheduledJobTask {

    private static final Logger LOG               = LoggerFactory.getLogger(CheckDataSourceTableJobTask.class);
    private static final String DEFAULT_MYSQL_SQL = new String(
        "SELECT TABLE_ROWS as rowSize,(DATA_LENGTH/1024/1024) as indexSize FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='%s'");
    private AppRuleService      appRuleService;

    @Override
    public boolean checkTask() throws JobExecutionException {
        return true;
    }

    @Override
    public void initTask() throws JobExecutionException {
        if (this.appRuleService == null) this.appRuleService = SpringContextUtil.getBean("appRuleService");
    }

    @Override
    public void runTask() throws JobExecutionException {
        String checkSql = StringUtils.EMPTY;
        try {
            List<AppRuleBO> appRuleBOs = appRuleService.findAllAppRuleBO();
            for (AppRuleBO appRuleBO : appRuleBOs) {
                DataSourceWrapper dataSourceWrapper = LoadDatasourceJobTask.getAppDataSources()
                    .get(appRuleBO.getDatasourceId());
                if (dataSourceWrapper == null) {
                    continue;
                }
                if (dataSourceWrapper.getDbType().equals(DataBaseType.MySql.getTypeFullName())) {
                    checkSql = String.format(DEFAULT_MYSQL_SQL, appRuleBO.getTableExpression());
                    try {
                        TableCheck tableCheck = dataSourceWrapper.queryForTableCheck(checkSql);
                        if (tableCheck != null) {
                            appRuleBO.setRowSize(tableCheck.getRowSize());
                            appRuleBO.setIndexSize(tableCheck.getIndexSize());
                            appRuleService.updateAppRuleBOById(appRuleBO);
                        }
                    } catch (EmptyResultDataAccessException e) {
                        LOG.error("table not exist! table:" + appRuleBO.getTableExpression());
                        continue;
                    }
                }
            }
            LOG.info("complete check datasource table size !");
        } catch (Exception e) {
            LOG.error("check datasource table size is error! exception:" + e + ",checkSql=" + checkSql);
        }
    }

}
